using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NCT.Framework;
using System.Data;
using System.Data.Common;
using NCT.Framework.Database;

namespace VISS.API.Commons {
	class BodyDA {

		private const string SP_Delete = "dbo.Body_Delete";
		private const string SP_GetAll = "dbo.Body_GetAll";
		private const string SP_Insert = "dbo.Body_Insert";
		private const string SP_Update = "dbo.Body_Update";

		public static BodyEnt CreateFromReader(IDataReader reader) {
			BodyEnt item = new BodyEnt();
			item.ID = ConvertUtils.ToShort(reader["ID"]);
			item.Name = ConvertUtils.ToString(reader["Name"]);
			item.Order = ConvertUtils.ToByte(reader["Order"]);
			return item;
		}

		public static int Delete(short iD, DbConnection dbCon, DbTransaction dbTrans) {
			int result = -1;
			Database db = Database.CreateDatabase(ConfigInfo.ConnectionName);
			using (DbCommand cmd = db.CreateStoredCommand(SP_Delete)) {
				db.AddParameter(cmd, "ID", iD);
				if (dbCon != null && dbTrans != null) {
					result = db.ExecuteNonQuery(cmd, dbCon, dbTrans);
				}
				else {
					result = db.ExecuteNonQuery(cmd);
				}
			}
			return result;
		}

		public static List<BodyEnt> GetAll(DbConnection dbCon, DbTransaction dbTrans) {
			List<BodyEnt> result = new List<BodyEnt>();
			Database db = Database.CreateDatabase(ConfigInfo.ConnectionName);
			using (DbCommand cmd = db.CreateStoredCommand(SP_GetAll)) {
				using (IDataReader reader = db.ExecuteReader(cmd)) {
					while (reader.Read()) {
						result.Add(CreateFromReader(reader));
					}
				}
			}
			return result;
		}

		public static int Insert(BodyEnt item, DbConnection dbCon, DbTransaction dbTrans) {
			int result = -1;
			Database db = Database.CreateDatabase(ConfigInfo.ConnectionName);
			using (DbCommand cmd = db.CreateStoredCommand(SP_Insert)) {
				db.AddParameterOuter(cmd, "ID", DbType.Int16);
				db.AddParameter(cmd, "Name", item.Name);
				db.AddParameter(cmd, "Order", item.Order);

				if (dbCon != null && dbTrans != null) {
					result = db.ExecuteNonQuery(cmd, dbCon, dbTrans);
					item.ID = ConvertUtils.ToShort(cmd.Parameters["ID"].Value);
				}
				else {
					result = db.ExecuteNonQuery(cmd);
					item.ID = ConvertUtils.ToShort(cmd.Parameters["ID"].Value);
				}
			}
			return result;
		}

		public static int Update(BodyEnt item, DbConnection dbCon, DbTransaction dbTrans) {
			int result = -1;
			Database db = Database.CreateDatabase(ConfigInfo.ConnectionName);
			using (DbCommand cmd = db.CreateStoredCommand(SP_Update)) {
				db.AddParameter(cmd, "ID", item.ID);
				db.AddParameter(cmd, "Name", item.Name);
				db.AddParameter(cmd, "Order", item.Order);
				if (dbCon != null && dbTrans != null) {
					result = db.ExecuteNonQuery(cmd, dbCon, dbTrans);
				}
				else {
					result = db.ExecuteNonQuery(cmd);
				}
			}
			return result;
		}

	}
}